<?php

namespace app\console\controller;

use app\common\service\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class FriendChatLog extends Command
{
    protected function configure()
    {
        $this->setName('chatlog:friend')->setDescription('run chatlog of friend to db');
    }

    protected function execute(Input $input, Output $output)
    {
        $redis = new Redis();
        $keys = $redis->keys('rec:friend:*');
        foreach ($keys as $key){
            $len = $redis->lLen($key);
            if($len > 200){
                $contents = $redis->lRange($key,0,$len-100);
                $friend_chat_log = [];
                foreach ($contents as $i=>$content){
                    $content = json_decode($content,true);
                    $friend_chat_log[$i]['send_uid'] = $content['mine']['id'];
                    $friend_chat_log[$i]['receive_uid'] = $content['to']['id'];
                    $friend_chat_log[$i]['send_content'] = $content['mine']['content'];
                    $friend_chat_log[$i]['send_time'] = round($content['to']['timestamp']/1000);
                }
                $re = model('common/friendChatLog')->saveAll($friend_chat_log);
                if($re){
                    $redis->lTrim($key,$len-99,-1);
                }
            }
        }
    }
}